package com.vxdata.utils.modules.utils.zstp;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

/**
 * 从jsonStr中解析 字段名称
 */
public class JsonParserUtil {

    public static TreeMap<String, String> analysisJson(String jsonStr) {
        return analysisJson(jsonStr, null, new TreeMap<>());
    }

    /**
     * 将jsonStr 按照层级拆分为map
     *
     * @param jsonStr   要处理的json字符串
     * @param flag_path 每次递归的前缀路径
     * @param jsonMap   唯一的map
     * @return
     */
    private static TreeMap<String, String> analysisJson(String jsonStr, String flag_path, TreeMap<String, String> jsonMap) {
        jsonStr = jsonStr.replaceAll("\\s", "");
        if (jsonStr.charAt(0) == '[') {
            JSONArray jsonArray = JSON.parseArray(jsonStr);
            for (int i = 0; i < jsonArray.size(); i++) {
                Object o = jsonArray.get(i);
                if (!(o instanceof JSONObject)) {
                    continue;
                }
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                for (String key : jsonObject.keySet()) {
                    Object object = jsonObject.get(key);
                    String path = StringUtils.isNotBlank(flag_path) ? flag_path + "@" + key : key;
                    jsonMap.put(path, object.getClass().getSimpleName());
                    if (object instanceof JSONObject) {
                        analysisJson(object.toString(), path, jsonMap);
                    } else if (object instanceof JSONArray) {
                        analysisJson(object.toString(), path, jsonMap);
                    }
                }
            }
        } else if (jsonStr.charAt(0) == '{') {
            JSONObject jsonObject = JSON.parseObject(jsonStr);
            for (String key : jsonObject.keySet()) {
                Object object = jsonObject.get(key);
                String path = StringUtils.isNotBlank(flag_path) ? flag_path + "@" + key : key;

                jsonMap.put(path, object.getClass().getSimpleName());
                if (object instanceof JSONObject) {
                    analysisJson(object.toString(), path, jsonMap);
                } else if (object instanceof JSONArray) {
                    analysisJson(object.toString(), path, jsonMap);
                }
            }
        }
        return jsonMap;
    }


    // TODO 只适应JSONObject的情况
    public static List<ColVo> parseJson(String jsonString) {
        jsonString = jsonString.replaceAll("\\s", "");
        JSONObject jsonObject = JSON.parseObject(jsonString);
        List<ColVo> colVoList = new ArrayList<>();
        for (String key : jsonObject.keySet()) {
            Object value = jsonObject.get(key);
            ColVo vo = new ColVo();
            vo.setColName(key);
            vo.setColType(value.getClass().getSimpleName());
            if (value instanceof JSONObject) {
                parseJsonObject((JSONObject) value, vo);
            } else if (value instanceof JSONArray) {
                parseJsonArray((JSONArray) value, vo);
            }
            colVoList.add(vo);
        }
        return colVoList;
    }

    private static void parseJsonObject(JSONObject jsonObject, ColVo parent) {
        for (String key : jsonObject.keySet()) {
            Object value = jsonObject.get(key);
            ColVo colVo = new ColVo();
            colVo.setColName(key);
            colVo.setColType(value.getClass().getSimpleName());

            if (value instanceof JSONObject) {
                // 处理嵌套对象
                parseJsonObject((JSONObject) value, colVo);
            } else if (value instanceof JSONArray) {
                // 处理嵌套数组
                parseJsonArray((JSONArray) value, colVo);
            }
            List<ColVo> childList = parent.getChildList();
            if (childList != null) {
                parent.getChildList().add(colVo);
            } else {
                List<ColVo> colVoList = new ArrayList<>();
                colVoList.add(colVo);
                parent.setChildList(colVoList);
            }
        }
    }

    private static void parseJsonArray(JSONArray jsonArray, ColVo parent) {
        Object value = jsonArray.get(0);
        if (value instanceof JSONObject) {
            // 处理嵌套对象
            parseJsonObject((JSONObject) value, parent);
            parent.setSubColType("ROW");
        } else if (value instanceof JSONArray) {
            // 处理嵌套数组
            parseJsonArray((JSONArray) value, parent);
        } else {
            parent.setSubColType(value.getClass().getSimpleName());
        }
    }


    public static void main(String[] args) {
//        String jsonStr = "{\"k8s_app_name\":\"roc\",\"json_extract\":{\"data\":{\"volume\":6,\"rcu\":{\"battery\":{\"temperature\":32,\"chargingStatus\":1,\"percent\":99,\"PArr\":[{\"id\":1,\"name\":\"孙悟空\"},{\"id\":2,\"name\":\"猪八戒\"}]}},\"robotStatus\":1,\"asrStatus\":1},\"serviceCode\":\"\",\"resultCode\":0,\"rcuId\":\"5013951A62CB\",\"source\":\"ROC\",\"robotId\":\"5013951A62CB\",\"resultInfo\":\"\",\"accountId\":\"AZ019179\",\"robotType\":\"patrol\",\"rodType\":\"reportMetrics\",\"tenantId\":\"patrol_jindi3\",\"guid\":\"9c20192006b845fd90714d5069b93d8b\",\"tag\":\"\",\"moduleId\":\"reportStatus\",\"timestamp\":\"2023-03-31T23:59:58.672+08:00\"},\"label\":\"bj-prod-221_roc_roc_roc-operation-service_harixaudit\",\"k8s_svc_name\":\"roc-operation-service\",\"k8s_env_name\":\"bj-prod-221\",\"output\":\"eskafka\",\"arr\":[\"1\"],\"arrObj\":[{\"id\":1,\"name\":\"孙悟空\"},{\"id\":2,\"name\":\"猪八戒\"}]}";
        String jsonStr = "[{\"title\":\"协议\",\"field\":\"protocol\",\"isnull\":\"N\"},{\"title\":\"主机\",\"field\":\"host\",\"isnull\":\"N\"},{\"title\":\"端口号\",\"field\":\"port\",\"isnull\":\"N\"},{\"title\":\"用户名\",\"field\":\"username\",\"isnull\":\"N\"},{\"title\":\"密码\",\"field\":\"password\",\"isnull\":\"N\"},{\"title\":\"路径\",\"field\":\"path\",\"isnull\":\"N\"}]";
        System.out.println(jsonStr);
        TreeMap<String, String> stringStringTreeMap = analysisJson(jsonStr, null, new TreeMap<>());
        System.out.println(stringStringTreeMap);
        List<ColVo> colVos = parseJson(jsonStr);
        String s = JSON.toJSONString(colVos);
        System.out.println(s);


    }


}

@Data
class ColVo {
    /**
     * json的key
     */
    private String colName;
    /**
     * json的value类型
     */
    private String colType;
    /**
     * colType为Array类型时才需要设置
     */
    private String subColType;
    /**
     * json的嵌套子集的集合
     */
    private List<ColVo> childList;
}
